#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "InetAddr.hpp"
using namespace std;

void Usage(string proc)
{
    cout << "Usage:\n\t" << "please input: " << proc << " serverip serverport" << endl;
}

int main(int argc, char *argv[])
{
    // 处理输入连接服务器的IP地址和端口号
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }
    string serverip = argv[1];
    uint16_t serverport = stoi(argv[2]);
    // 创建客户端sockfd套接字
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if(sockfd < 0)
    {
        cout << "socket error..." << endl;
        cout << strerror(errno) << "  " << errno << endl;
        exit(1);
    }
    // 构建目标主机的socket信息
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr = inet_addr(serverip.c_str());
    // 进行服务通信
    string message;
    while(true)
    {
        // 发送数据
        cout << "Please Input# ";
        getline(cin, message);
        sendto(sockfd, message.c_str(), message.size(), 0, (struct sockaddr*)&server, sizeof(server));
        // 接收数据
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        char buffer[1024];
        ssize_t n = recvfrom(sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr*)&peer, &len);

        if(n > 0)
        {
            InetAddr addr(peer);
            buffer[n] = 0;
            cout << "server echo[serverip:" << addr.Ip() 
                 << ",serverport:" << addr.Port() << "]"
                 << "# " << buffer << endl;
        }
    }
    return 0;
}